/**
 * 
 */
package com.xianshijian.oauth.server.controller;

import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xianshijian.oauth.common.entity.OAuth;
import com.xianshijian.oauth.common.utils.CookieUtils;
import com.xianshijian.oauth.common.utils.JsonUtils;
import com.xianshijian.oauth.server.cache.CacheKey;
import com.xianshijian.oauth.server.entity.ThirdParty;
import com.xianshijian.oauth.server.service.OAuthService;
import com.xianshijian.oauth.server.service.ThirdPartyService;

/**
 * 授权接口：第三方调用 
 * 1.验证第三方参数
 * 2.调用 验证用户登录状态接口，返回登录状态 
 * 3.根据登录状态返回页面给用户 
 *  	1.未登录，返回登录并授权页面
 * 		2.已登录，返回授权页面
 * 
 * @author ptzhuf
 *
 */
@Controller
public class AuthController {

	@Autowired
	private OAuthService oAuthService;
	@Autowired
	private ThirdPartyService thirdPartyService;

	private static final Logger LOG = LoggerFactory.getLogger(AuthController.class);

	@RequestMapping(value = "/oauth2/auth", method = RequestMethod.GET)
	public String auth(HttpServletRequest request, HttpServletResponse response, RedirectAttributes attr
			, Model model)throws URISyntaxException {
		try {
			//*********************************获取参数*********************************//
			String thirdPartyId = request.getParameter(OAuth.OAUTH_THIRD_PARTY_ID);
			String redirectURL = request.getParameter(OAuth.OAUTH_REDIRECT_URL);
			String state = request.getParameter(OAuth.OAUTH_STATE);
			String scope = request.getParameter(OAuth.OAUTH_SCOPE); 
			String sjkSessionId = CookieUtils.getCookieValue(request,OAuth.OAUTH_SESSION_ID);

			
			//*********************************验证参数*********************************//
			if (StringUtils.isBlank(thirdPartyId) || !oAuthService.checkThirdPartyId(thirdPartyId)) {
				attr.addAttribute("state", state);   
            	attr.addAttribute("code", null); 
				attr.addAttribute("status", OAuth.StatusCode.THIRD_PARTY_ID_ERROR);
				attr.addAttribute("msg", "客户端验证失败，失败原因：错误的thirdParty_id");
				return "redirect:" + redirectURL;			
			}

			if (StringUtils.isBlank(redirectURL)) {
				attr.addAttribute("state", state);   
            	attr.addAttribute("code", null); 
				attr.addAttribute("status", OAuth.StatusCode.REDIRECT_URL_ERROR);
				attr.addAttribute("msg", "客户端验证失败，失败原因：错误的redirect_url");
				return "redirect:" + redirectURL;
			}

			if (StringUtils.isBlank(state)) {
				attr.addAttribute("state", state);   
            	attr.addAttribute("code", null); 
				attr.addAttribute("status", OAuth.StatusCode.STATE_ERROR);
				attr.addAttribute("msg", "客户端验证失败，失败原因：错误的state");
				return "redirect:" + redirectURL;
			}

			if (StringUtils.isBlank(scope)) {
				attr.addAttribute("state", state);   
            	attr.addAttribute("code", null); 
				attr.addAttribute("status", OAuth.StatusCode.SCOPE_ERROR);
				attr.addAttribute("msg", "客户端验证失败，失败原因：错误的scope");
				return "redirect:" + redirectURL;
				
			}
			
			//验证用户是否登录
			HashMap<String,String> map = JsonUtils.jsonToPojo(oAuthService.checkUserLogin(sjkSessionId), HashMap.class);
			

			
			//*********************************存入缓存中，给确认授权接口传递参数*********************************//
			Map<String, Object> redisKeyMap = new HashMap<String, Object>();
			redisKeyMap.put(OAuth.OAUTH_THIRD_PARTY_ID, thirdPartyId);
			redisKeyMap.put(OAuth.OAUTH_REDIRECT_URL, redirectURL);
			redisKeyMap.put(OAuth.OAUTH_STATE, state);
			redisKeyMap.put(OAuth.OAUTH_SCOPE, scope);
			String stamp = UUID.randomUUID().toString();
			redisKeyMap.put(OAuth.OAUTH_STAMP, stamp);
			String challenge = map.get("challenge");		
			redisKeyMap.put(OAuth.OAUTH_CHALLENGE, challenge);
			String redisKey = CacheKey.createSessionIdTempKey(sjkSessionId);
			thirdPartyService.putCacheKey(redisKey, redisKeyMap);
			
			
			//*********************************返回给前端的参数*********************************//
			ThirdParty thirdParty = thirdPartyService.findByThirdPartyId(thirdPartyId);
			model.addAttribute("logo_url", thirdParty.getLogoUrl());
			model.addAttribute("app_name", thirdParty.getServiceName());
			StringBuilder sb = new StringBuilder();
			model.addAttribute("stamp", sb.append("{\"challenge\":\"").append(challenge).append("\",").append("\"stamp\":\"").append(stamp).append("\"}").toString());  //{"stamp":"adssdqwweqwewq" }
			
			//*********************************已登录:返回确认授权页面,未登录:返回登录并授权页面*********************************//
			String isLogin = map.get("isLogin");
			if (isLogin.equals("1")) {
				return "login/confirmLogin";
			} else {
				return "login/empowerLogin";
			}
		} catch (Exception e) {
			// 打印错误日志
			String msg = "调用auth出错 : {" + e.getMessage() + "}";
			String errMsg = new StringBuilder(msg).append(", 请求参数为:[{}]").toString();
			LOG.error(errMsg, Arrays.asList(new Object[] { request }));
			LOG.error("错误信息:", e);
			throw new RuntimeException(msg, e);
		}
	}

}
